using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using AjaxPro;

using CMS.Core.DataInterfaces;
using CMS.Data;
using CMS.Core.Domain;
using CMS.Presenters.Presenters;
using CMS.Presenters.Views;
using CMS.Data.Common;

namespace CMS.Web.ListManager
{
    public partial class AddNguoiSuDung : BaseUserControl, IAddNguoiSuDungView
    {
        private AddNguoiSuDungPresenter presenter;
        // For Phong ban
        IList<PhongBan> pbList;
        DataTable tkLDAPList;
        IList<NhomNguoiSuDung> gList;
        IList<ChucNang> cnList;
        IList<VaiTro> vtList;

        public AddNguoiSuDung()
        {
            this.presenter = new AddNguoiSuDungPresenter(this, NHibernateDaoFactory.Instance.GetNguoiSuDungDao());
            this.tkLDAPList = presenter.tkLDAPList;
            
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            // For Ajax
            this.RaiseClientEvent();
            if (!this.IsPostBack)
            {
                this.presenter.LoadViewFromModel();

                // For Phong ban
                this.drpPhongBan.DataSource = this.PhongBanList;
                drpPhongBan.DataTextField = "TenPhongBan";
                drpPhongBan.DataValueField = "ID";
                this.drpPhongBan.DataBind();
                
                this.drpGroup.DataSource = this.GroupList;
                this.drpGroup.DataBind();

                if (this.presenter.IsUsingLDAP)
                {
                    // Bind data to radio list
                    this.BindrdoList(this.radTaiKhoan, this.tkLDAPList, "UserName", "UserName");
                    this.radTaiKhoan.Visible = true;
                    //this.txtTenTruyCap.Visible = false;
                    this.txtMatKhau.Visible = false;
                }
                else 
                {
                    //this.txtTenTruyCap.Visible = true;
                    this.div_TaiKhoan.Visible = false;
                    this.txtMatKhau.Visible = true;
                    this.radTaiKhoan.Visible = false;
                }
            }
            this.btnOK.Attributes.Add("onclick", "return CheckInput(0);");
            this.btnOKC.Attributes.Add("onclick", "return CheckInput(1);");
            //this.radTaiKhoan.Attributes.Add("onclick", "return CheckAcountLDAP();");
        }

        // For Ajax to validdate
        protected void RaiseClientEvent()
        {
            Utility.RegisterTypeForAjax(typeof(CMS.Presenters.Presenters.AddNguoiSuDungPresenter));
        }

        public string Message
        {
            set { //lblMessage.Text = value; 
            }
        }

        public NguoiSuDung NguoiSuDungToAdd
        {
            get
            {
                NguoiSuDung obj = new NguoiSuDung();
                obj.TenNguoiSuDung = txtName.Text.Trim();
                obj.MaPhongBan = drpPhongBan.SelectedValue;
                //obj.MaPhongBan = "9A22666B-B88E-4564-8156-979BE5410FB8";
                obj.ChucVu = txtChucVu.Text.Trim();
                if (this.presenter.IsUsingLDAP)
                {
                    try
                    {
                        obj.TenTruyCap = radTaiKhoan.SelectedItem.Text;
                    }
                    catch
                    {
                    }
                }
                else
                {
                    obj.TenTruyCap = txtTenTruyCap.Text.Trim();
                }
                obj.MatKhau = txtMatKhau.Text.Trim();
                if (drpGroup.SelectedValue != "")
                {
                    obj.MaNhom = Convert.ToByte(drpGroup.SelectedValue);
                }
                obj.ChucNang = this.VaiTro;

                String ids = "";                
                IList<ChucNang> cnList = new List<ChucNang>();
                if (ids != "")
                {
                    cnList = this.presenter.GetFunctions(ids);
                }
                obj.ChucNangs = cnList;

                obj.TrangThai = Convert.ToBoolean(radStatus.SelectedValue);
                obj.ThuTu = Convert.ToInt16(txtThuTu.Text.Trim());
                return obj;
            }
        }

        public IList<PhongBan> PhongBanList
        {
            get { return this.pbList; }
            set { this.pbList = value; }
        }

        public DataTable TaiKhoanLDAPList
        {
            get { return this.tkLDAPList; }
        }

        public IList<NhomNguoiSuDung> GroupList
        {
            set { this.gList = value; }
            get { return this.gList; }
        }

        public IList<ChucNang> ChucNangList
        {
            set { this.cnList = value; }
            get { return this.cnList; }
        }

        public IList<VaiTro> VaiTroList
        {
            set { this.vtList = value;
                this.chkRoles.DataSource = value;
                this.chkRoles.DataBind();
            }
            get { return this.vtList; }
        }

        public String VaiTro
        {
            get
            {
                String ids = "";
                foreach (ListItem item in chkRoles.Items)
                {
                    if (item.Selected) ids += (ids == "") ? item.Value : "," + item.Value;
                }
                return ids;
            }
            set
            {
                foreach (ListItem item in chkRoles.Items)
                {
                    item.Selected = false;
                    item.Enabled = true;
                }
                String[] ids = value.Split(new Char[] { ',' });
                for (int i = 0; i < ids.Length; i++)
                {
                    ListItem item = chkRoles.Items.FindByValue(ids[i]);
                    if (item != null)
                    {
                        item.Selected = true;
                        item.Enabled = false;
                    }
                }
            }
        }

        public bool BindrdoList(RadioButtonList rdolist, DataTable dtb, string ValueField, string TextField)
        {
            bool bKetqua = false;
            try
            {
                rdolist.DataValueField = ValueField;
                rdolist.DataTextField = TextField;
                rdolist.DataSource = dtb.DefaultView;
                rdolist.DataBind();
                bKetqua = true;
            }
            catch (Exception e)
            {
            }
            return bKetqua;
        }

        public bool isConnectLDAP()
        {
            return presenter.IsUsingLDAP;
        }

        public String ListLDAPAccount()
        {
            string strRt="";
            if (presenter.IsUsingLDAP)
            {
                for (int i = 0; i < this.tkLDAPList.Rows.Count; i++)
                {
                    strRt = strRt + tkLDAPList.Rows[i][1].ToString() + ";";
                }

                if (strRt.Length > 0)
                    return strRt.Remove(strRt.Length - 1);
                else
                {
                    return strRt;
                }
            }
            return strRt;
        }


        private void BuildTreeRoot(TreeView trv, IList<ChucNang> cnList)
        {
            trv.Nodes.Clear();
            if (cnList.Count == 0)
                return;
            foreach (ChucNang cn in cnList)
            {
                if (cn.MaCapCha == 0)
                {
                    TreeNode nodetmp = new TreeNode(cn.TenChucNang, cn.ID.ToString());
                    nodetmp.Target = cn.ID.ToString();
                    trv.Nodes.Add(nodetmp);
                    nodetmp.ShowCheckBox = true;
                    nodetmp.SelectAction = TreeNodeSelectAction.None;
                    BuildTree(nodetmp, cnList);
                    //nodetmp.Expand();
                }
            }
        }

        private void BuildTree(TreeNode node, IList<ChucNang> cnList)
        {
            if (cnList.Count == 0)
                return;
            foreach (ChucNang cn in cnList)
            {
                if (cn.MaCapCha.ToString() == node.Value)
                {
                    TreeNode nodetmp = new TreeNode(cn.TenChucNang, cn.ID.ToString());
                    nodetmp.Target = cn.ID.ToString();
                    nodetmp.ShowCheckBox = true;
                    nodetmp.SelectAction = TreeNodeSelectAction.None;
                    node.ChildNodes.Add(nodetmp);
                    BuildTree(nodetmp, cnList);
                    //nodetmp.Expand();
                }
            }
        }

        private void CheckExistRoots(TreeView trv, IList<ChucNang> cnList)
        {
            foreach (TreeNode node in trv.Nodes)
            {
                foreach (ChucNang cn in cnList)
                {
                    if (node.Value == cn.ID.ToString())
                    {
                        node.Checked = true;
                        node.SelectAction = TreeNodeSelectAction.None;
                        CheckExistNodes(node, cnList);
                    }
                }
            }
        }

        private void CheckExistNodes(TreeNode parent, IList<ChucNang> cnList)
        {
            foreach (TreeNode node in parent.ChildNodes)
            {
                foreach (ChucNang cn in cnList)
                {
                    if (node.Value == cn.ID.ToString())
                    {
                        node.Checked = true;
                        CheckExistNodes(node, cnList);
                    }
                }

            }
        }

        private String GetCheckedNodeIds(TreeNode parent)
        {
            String ids = "";
            foreach (TreeNode node in parent.ChildNodes)
            {
                if (node.Checked)
                {
                    ids += (ids == "") ? node.Value : "," + node.Value;
                    String temp = GetCheckedNodeIds(node);
                    if (temp != "")
                    {
                        ids += "," + temp;
                    }
                }
            }
            return ids;
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            presenter.AddObj(Page.IsValid);
            this.btnCancel_Click(this, null);
        }

        protected void btnOKC_Click(object sender, EventArgs e)
        {
            presenter.AddObj(Page.IsValid);
            this.txtName.Text = "";
            this.txtChucVu.Text = "";
            this.txtTenTruyCap.Text = "";
            this.txtMatKhau.Text = "";
            this.txtName.Focus();
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect(this.BaseUrl + "&action=VIEW");
        }

        protected void drpGroup_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.VaiTro = this.presenter.GetRolesOfGroup(drpGroup.SelectedValue);
            this.presenter.GetFunctionsNotOfGroup(drpGroup.SelectedValue);
            //BuildTreeRoot(trvFunctions, this.ChucNangList);
        }
    }
}